<script setup>
import _ from 'lodash'
import DeptCreate from './dept-create.vue';
import {useCommonStore} from "@jzl/stores";
import {computed, onMounted, ref, reactive, toRefs, watch, nextTick} from "vue";
import {api} from "@jzl/api";
import {DFT_ICONS} from "@jzl/icons";
import {$WinDeptUsers} from "@jzl/comps-mg";

const {
  winName,
  items,
  loading,
  currentData,
  expandedKeys,
  treeSetting,
  showCreate,
  modId,
  isView,
  userInfoTitle,
  userInfoShow,
  userInfo
} = toRefs(reactive({
  winName: '新增',
  items: [],
  loading: false,
  currentData: {},

  expandedKeys: [],
  // checkedKeys: [],
  treeSetting: {
    id: 'nodeId',
    children: 'subs',
    label: 'name'
  },

  // currentNode: null,
  // currentResolve: null,

  showCreate: false,
  modId: null,
  isView: false,

  // menuId: null,

  userInfoTitle: '',
  userInfoShow: false,
  userInfo: {}
}));

const queryText = ref('');
const itreeRef = ref(null)

const project = computed(() => {
  return useCommonStore().project;
});

const loginUser = computed(() => {
  return useCommonStore().loginUser;
});

const canEdit = computed(() => {
  let editing = true;

  if (currentData.value && currentData.value.project_id === -1) {
    if (loginUser.value?.type === '_SUPER') {
      editing = true;
    } else {
      editing = false;
    }
  }

  return editing;
})

const actionDisabled = computed(() => {
  return !currentData.value || currentData.value.dept_id <= 0
})

watch(() => project.value, () => {
  init()
})

watch(() => queryText.value, (val) => {
  itreeRef.value.filter(val)
})

onMounted(async () => {
  await init()
})

const init = async () => {
  let iProject = _.cloneDeep(project.value);
  if (!iProject) return;

  iProject.name = iProject.project_name;
  iProject.subs = [];
  iProject.isRoot = true;
  iProject.nodeId = -1;

  currentData.value = iProject;
  await refreshCurrentNode()

  items.value = [ iProject ];
}

const close = (flag) => {
  emit('close', flag);
}

const refreshCurrentNode = () => {
  chooseNode(currentData.value, true);
}

const refreshParentNode = () => {

  let parentKey = _.get(currentData.value, 'parent_id');

  if (parentKey < 0 && parentKey !== -1) {
    return;
  }
  if (parentKey > 0) {
    parentKey = 'D_' + parentKey;
  }

  let parentNode = itreeRef.value.getNode(parentKey);
  chooseNode(_.get(parentNode, 'data'), true);
}

const handleClick = async (data, node, ele) => {
  currentData.value = data;
  // this.form.value = _.cloneDeep(currentData.value);

  await chooseNode(data);
}

const handleClearSelect = () => {
  let prj = items.value[0];
  itreeRef.value.setCurrentKey(prj);
  currentData.value = prj;
}

const chooseNode = async (data, force = false) => {  // 通过data 选择节点

  if (!data) return;

  let parent_id = -1;

  currentData.value = data;

  if (data.isRoot) {
    parent_id = -1;
  } else if (data.dept_id) {
    parent_id = data.dept_id;
  } else {
    return;
  }

  if (data.loaded && !force) {
    return;
  }

  loading.value = true;

  let deptUser = await api.dept.getDeptsAndUsersByDeptId(parent_id);
  let depts = _.get(deptUser, 'depts', []);
  let users = _.get(deptUser, 'users', []);

  _.each(depts, d => {
    d.nodeId = 'D_' + d.dept_id;
    d.name = d.dept_name;
    d.isLeaf = false;
    d.isGroup = true;
  });

  _.each(users, u => {
    u.nodeId = 'U_' + u.id;
    u.isLeaf = true;
    u.isGroup = false;
  });

  // let subs = _.concat(depts, users);

  loading.value = false;
  // this.$set(data, 'loading', false);
  // this.$set(data, 'loaded', true);
  // this.$set(data, 'subs', depts);
  // this.$set(data, 'users', users);
  data.loading = false;
  data.loaded = true;
  data.subs = depts;
  data.users = users;
  expandedKeys.value = [data.nodeId];
}

const handleShowAddUser = () => {
  $WinDeptUsers({
    mode: 'USER',
    onConfirm: async (data) => {
      let users = _.get(data, 'users');
      let ids = _.map(users, 'id');
      let ret = await api.admin.batUpdateAdmin(ids, {dept_id: currentData.value.dept_id});

      if (ret) {
        refreshCurrentNode();

        _.each(users, u => {
          let key = 'D_' + u.dept_id;
          let node = itreeRef.value.getNode(key);

          if (node && node.data) {
            // this.$set(node.data, 'loaded', false);
            node.data.loaded = false;
          }
        });
      }
    }
  });
}

const handleShowDelete = async () => {

}

const filterNode = (value, data) => {
  if (!value) return true;
  if (!data.name) return true;
  return data.name.indexOf(value) !== -1;
}

const closeWin = (flag) => {
  showCreate.value = false;
  if (flag) {
    if (modId.value) {
      refreshParentNode();
    } else {
      refreshCurrentNode();
    }
  }
}

const handleShowCreateWin = () => {
  showCreate.value = true;
  modId.value = null;
  isView.value = false;
  winName.value = '新增部门';
}

const handleShowView = (it) => {
  modId.value = it.id;
  showCreate.value = true;
  isView.value = true;
}

const handleShowEditWin = () => {

  let it = currentData.value;
  if (!it && it.dept_id <= 0) {
    return;
  }
  modId.value = it.dept_id;
  showCreate.value = true;
  isView.value = false;
  winName.value = '修改部门【' + _.get(it, 'dept_name') + '】';
}

const handleRemoveDept = async () => {
  let it = currentData.value;
  if (!it && it.dept_id <= 0) return;

  let ret = await api.dept.removeDept(it.dept_id);

  if (ret) {
    init();
  }
}

const handleDownDeptList = () => {
  $fileUtils.downloadFile("/assets/tpl/import_tpl_dept.xlsx");
}

const handleShowUserInfo = (u) => {
  if (!u) return;
  let name = _.get(u, 'nickname') || _.get(u, 'loginname');
  userInfo.value = u;
  userInfoShow.value = true;
  userInfoTitle.value = `${name}的基本信息`;
}
</script>

<template>
  <div class="mb-wrap">
    <!--<div class="mb-tree-wrap">-->
    <div class="mb-tree-wrap">
      <el-input
        v-model="queryText"
        class="thin-search-input"
        clearable
        placeholder="按名称搜索"
      ></el-input>
      <perfect-scrollbar
        :settings="{}"
        class="mb-tree"
        @click="handleClearSelect()"
        style="background: #FFF;">
        <el-tree
          ref="itreeRef"
          class="menu-custom-tree"
          :data="items"
          node-key="nodeId"
          :highlight-current="true"
          :default-expanded-keys="expandedKeys"
          :props="treeSetting"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          default-expand-all
          @click.native.stop
          @node-click="handleClick">
          <template #default="{ node, data }">
            <span class="menu-custom-tree-node">
              <span class="menu-custom-icon">
                <JIcon
                  v-if="data.loading"
                  :icon="DFT_ICONS.loadingSpinner"
                />
                <JIcon :icon="DFT_ICONS.dir"/>
              </span>
              <span v-text="data.name"></span>
            </span>
          </template>
        </el-tree>
      </perfect-scrollbar>
    </div>
    <!--</div>-->
    <div class="mb-info">
      <div class="dept-info">
        <h4>{{ currentData.name }}
          <template
            v-if="currentData.dept_code"
          ><span style="margin: 0px 5px;color:#CCC;">/</span>
            <span
              class="dept-info-code"
              v-copy="currentData.dept_code"
              v-tippy="{ arrow: true }"
              content="复制编码"
            >{{ currentData.dept_code }}</span>
          </template>
          <span
            class="dept-info-remark"
            v-if="currentData.remark"
            v-text="currentData.remark"
          ></span>
        </h4>
        <div class="actions" v-if="canEdit">
          <el-button
            size="small"
            type="text"
            :disabled="actionDisabled"
            @click="handleShowCreateWin()">
            <template #icon>
              <JIcon :icon="DFT_ICONS.add"/>
            </template>子部门
          </el-button>
          <el-button
            size="small"
            type="text"
            v-if="currentData?.dept_id > 0"
            :disabled="actionDisabled"
            @click="handleShowEditWin()">
            <template #icon>
              <JIcon :icon="DFT_ICONS.edit"/>
            </template>编辑
          </el-button>
          <el-button
            size="small"
            type="text"
            v-if="currentData?.dept_id > 0"
            :disabled="actionDisabled"
            @click="handleRemoveDept()"
          >
            <template #icon>
              <JIcon :icon="DFT_ICONS.delete"/>
            </template>删除
          </el-button>
          <el-button
            size="small"
            type="text"
            :disabled="actionDisabled"
            @click="handleShowAddUser()">
            <template #icon>
              <JIcon :icon="DFT_ICONS.add"/>
            </template>
            人员
          </el-button>
          <!--<el-button size="mini" icon="el-icon-plus" type="text" :disabled="actionDisabled"
                     @click="handleDownDeptTpl()">下载导入模板 </el-button>-->

          <el-button
            size="small"
            type="text"
            :disabled="actionDisabled"
            style="margin-left:10px;"
            @click="handleDownDeptList(currentData.dept_id)">
            <template #icon>
              <JIcon :icon="DFT_ICONS.download"/>
            </template>
            下载模板
          </el-button>
          <DataImportBtn
            :type="2"
            @import-change="init"
            style="display: inline-block;margin-left: 10px;"/>
        </div>
      </div>
      <div class="dept-users">
        <!--<div class="actions" v-if="canEdit">
          <el-button size="mini" icon="el-icon-delete" type="text" :disabled="actionDisabled"
                     @click="handleShowDelete()">删除人员 </el-button>
        </div>-->
        <perfect-scrollbar
          :options="{
            suppressScrollX: true,
          }"
          class="user-card-wrap">
          <div
            class="user-card"
            v-for="u in currentData.users"
            @click="handleShowUserInfo(u)"
          >
            <div class="user-avatar">
              <img v-if="u?.avatar" :src="u.avatar"/>
              <JIcon v-else :icon="DFT_ICONS.userCircle" />
            </div>
            <div class="user-card-info">
              <h5 v-text="u.nickname"></h5>
              <p v-text="u.loginname"></p>
            </div>
          </div>
        </perfect-scrollbar>
      </div>
    </div>

    <el-dialog
      v-model="showCreate"
      :title="winName"
      top="60px"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <DeptCreate
        @close="closeWin"
        :mod-id="modId"
        :pid="currentData?.dept_id || -1"
        :show="showCreate"
        :is-view="isView"
      />
    </el-dialog>

    <el-drawer
      v-model="userInfoShow"
      :title="userInfoTitle"
      direction="rtl"
      size="740px">
      <div style="position: absolute;top: 50px;left: 0px;bottom: 0px;right: 0px;padding: 0px;overflow-y: auto;">
        <JzlForm
          form-code="_ADMIN"
          view-code="_USER_BRIEF_VIEW"
          :data-id="userInfo.id"
          :is-view="true"
        ></JzlForm>
      </div>
    </el-drawer>
  </div>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.mb-wrap {
  display: flex;
  height: 100%;

  .role-menu-item {
    margin-right: 10px;

    &.border {
      border: 1px solid #EEE;
    }
  }

  .mb-tree {
    padding-top: 5px;
    height: 100%;
    width: 300px;
    overflow: auto;
    border-right: 1px solid #EEE;

    .role-custom-tree-node {
      .el-checkbox {
        margin-right: 5px;
      }
    }
  }

  .mb-info {
    flex: 1;
    display: flex;
    flex-flow: column;

    .actions {
      padding: 3px 10px;
      text-align: right;
      /*position: absolute;*/
      top: 0px;
      left: 0px;
      right: 0px;
    }

    .dept-info {
      border-bottom: 1px solid #EEE;
      /*margin: 10px;*/
      padding: 0px;
      position: relative;
      background: #FEFEFE;
      text-align: left;
      display: flex;
      align-items: center;
      justify-content: space-between;

      h4, p {
        margin: 10px;
        cursor: pointer;
      }

      .dept-info-code {
        font-weight: bold;
        color: #409EFF;
      }

      .dept-info-remark {
        color: #999;
        font-size: 12px;
        margin-left: 10px;
      }
    }

    .dept-users {
      position: relative;
      flex: 1;
      padding-top: 5px;
      overflow-y: auto;

      .user-card-wrap {
        height: 100%;
        padding-top: 5px;
        padding-left: 10px;
      }

      .user-card {
        display: flex;
        align-items: center;
        margin-right: 10px;
        margin-bottom: 10px;
        border: 1px solid #EEEE;
        padding: 8px;
        border-radius: 5px;
        width: 180px;
        height: 60px;
        min-height: 55px;
        justify-content: flex-start;
        background: #FFF;
        transition: all .2s;
        float: left;
        cursor: pointer;

        .user-card-info {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .user-avatar {
          width: 36px;
          height: 36px;
          display: inline-flex;
          margin-right: 8px;

          img {
            /*width: 36px;
            height: 36px;
            margin-right: 8px;*/
            border-radius: 50%;
          }

          img, .j-icon {
            width: 100%;
            height: 100%;
          }
        }

        h5, p {
          margin: 0px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        p {
          margin: 0px;
          font-size: 12px;
          color: #999;
        }

        &:hover {
          border-color: #AAA;
          box-shadow: 5px 5px 6px #CCC;
          transform: scale(1.02);
        }
      }
    }
  }
}
</style>
